package cn.charmaine.basic.util;

import cn.charmaine.basic.jwt.JwtUtils;
import cn.charmaine.basic.jwt.Payload;
import cn.charmaine.basic.jwt.RsaUtils;
import cn.charmaine.basic.jwt.UserInfo;
import cn.charmaine.org.domain.Logininfo;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.PublicKey;

/**
 * 获取当前登录人信息
 */
public class LoginContext {
    public static final String JWT_RSA_PUBLIC = "hrm_auth_rsa.pub";
    public static Logininfo getCurrentUser(HttpServletRequest request){
        //获取公钥
        PublicKey publicKey = null;
        try {
            //从请求中获取token
            String token = request.getHeader("TOKEN");//json web token
            publicKey = RsaUtils
                    .getPublicKey(FileCopyUtils
                    .copyToByteArray(LoginContext.class.getClassLoader().getResourceAsStream(JWT_RSA_PUBLIC)));
            //解密token
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            return payload.getUserInfo().getLogininfo();
        } catch (IOException e) {
           e.printStackTrace();
           return null;
        }
        
    }
}
